package com.atguigu.shangrongbao.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.shangrongbao.core.pojo.dto.ExcelDictDto;
import com.atguigu.shangrongbao.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Api(tags = "excel导入数据")
@Slf4j
@RestController
@RequestMapping("/admin/core/dict")
public class EasyExcelController {
    @Autowired
    private DictService dictService;
    /**
     * 上传excel进行解析
     * @return
     */
    @ApiOperation("文件上传解析数据")
    @PostMapping("/upload")
    public R uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            dictService.parseExcelData(file.getInputStream());
            return R.ok("文件上传成功");
        }catch (Exception e){
            log.info(e.getMessage(), e);
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }
    }

    @ApiOperation("数据导出功能")
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        /**
         * 1. 查询数据
         * 2. 封装数据
         * 3. 写入数据
         */
        List<ExcelDictDto> allDict = dictService.getAllDict();
        // log.info("controller获取到的所有字典数据：{}", allDict);
        // return R.ok().put("data", allDict);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDto.class).sheet("模板").doWrite(allDict);

        // return null;
    }
}
